package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.dot.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapeer.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishMapper dishMapper;

    @Override
    //事务管理
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品到增强菜表
        this.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();

        //判断是否选择口味
        if (flavors != null && flavors.size() > 0) {
            //获取菜品id
            Long id = dishDto.getId();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
                //批量插入
                dishFlavorService.saveBatch(flavors);

            }
        }
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //从菜品表查询菜品信息
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish, dishDto);

        //查询当前菜品的口味信息
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //更新表的基本信息
        this.updateById(dishDto);
        //清除当前菜品对应口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        //添加当前设置的数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().map((item -> {
                    item.setDishId(dishDto.getId());
                    return item;
                })
        ).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public Boolean deleteByIds(List<Long> ids) {
        int result =dishMapper.deleteBatchIds(ids);
        return result>0;
    }

}
